package com.heakey.common.component;

import cn.hutool.core.util.StrUtil;
import com.heakey.common.constant.CacheKey;
import com.heakey.common.constant.CommonConstant;
import com.heakey.common.enums.BaseErrorCodeEnum;
import com.heakey.common.iface.IUserAuthService;
import com.heakey.common.redis.IRedisService;
import com.heakey.common.util.AssertBusUtils;
import com.heakey.common.util.TokenUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * @Description 用户授权服务
 * @Author Bing
 * @Date 2024/10/22 19:12
 */
@Slf4j
@Service
public class UserAuthService implements IUserAuthService {

    @Autowired
    private IRedisService redisService;

    @Override
    public String auth(String token, Long userId) {
        if(StrUtil.isBlank(token)){
            token = TokenUtil.createToken(userId.toString());
        }
        redisService.setValue(String.format(CacheKey.TOKEN_KEY, token), userId, CommonConstant.LOGIN_EFFECTIVETIME);
        return token;
    }

    @Override
    public Long isLogin(String token,boolean forceCheck) {
        Long userId = redisService.getValue(String.format(CacheKey.TOKEN_KEY, token),Long.class);
        if(forceCheck){
            AssertBusUtils.notNull(userId, BaseErrorCodeEnum.UNAUTHORIZED);
        }
        return userId;
    }

    @Override
    public void logout(String token) {
        redisService.delKey(String.format(CacheKey.TOKEN_KEY, token));
    }

    @Override
    public void defer(String token,Long deferSecond) {
        String key = String.format(CacheKey.TOKEN_KEY, token);
        Long expireSeconds = redisService.getKeyExpire(key) + deferSecond+CommonConstant.NUM_THREE;
        redisService.expire(key, expireSeconds.intValue());
    }
}